//
//  AppDelegate.m
//  werfgh
//
//  Created by QJY on 14-8-25.
//  Copyright (c) 2014年 dingshenwangluokeji. All rights reserved.
//

#import "AppDelegate.h"
#import "CallViewController.h"
#import "MoneyViewController.h"
#import "MeViewController.h"
#import "IponeViewController.h"
#import "MyTabBar.h"
#import "Header.h"
#import "DingSh.h"
#import "FMDBManager.h"
#import "AFNetworking.h"

#import "JimViewController.h"
#import "UMFeedback.h"
#import "UMessage.h"
#import <CoreTelephony/CTCallCenter.h>
#import <CoreTelephony/CTCall.h>

@implementation AppDelegate
{
    UITabBarController *_bar;
    MyTabBar *_mtb;
    UIButton *_btn0;
    UIButton *_btn1;
    UIButton *_btn2;
    UILabel *_labeh;
    UIImageView *_imafg ;
    UIImageView *splashScreen;
    CTCall* callPhone;
}
#define APPKEY @"54d1e070fd98c5def80005d7"

#define UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define _IPHONE80_ 80000
-(void)setPush:(NSDictionary*)launchOptions
{
    [UMFeedback setAppkey:APPKEY];
    
    NSDictionary *notificationDict = [launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if ([notificationDict valueForKey:@"aps"]) // 点击推送进入
    {
        [UMFeedback didReceiveRemoteNotification:notificationDict];
    }
    
    
    // with remote push notification
    [UMessage startWithAppkey:APPKEY launchOptions:launchOptions];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
    if(UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
    {
        //register remoteNotification types
        UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier = @"action1_identifier";
        action1.title=@"Accept";
        action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序
        
        UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];  //第二按钮
        action2.identifier = @"action2_identifier";
        action2.title=@"Reject";
        action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序，在后台处理
        action2.authenticationRequired = YES;//需要解锁才能处理，如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略；
        action2.destructive = YES;
        
        UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];
        categorys.identifier = @"category1";//这组动作的唯一标示
        [categorys setActions:@[action1,action2] forContext:(UIUserNotificationActionContextDefault)];
        
        UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert
                                                                                     categories:[NSSet setWithObject:categorys]];
        [UMessage registerRemoteNotificationAndUserNotificationSettings:userSettings];
        
    } else{
        //register remoteNotification types
        [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
         |UIRemoteNotificationTypeSound
         |UIRemoteNotificationTypeAlert];
    }
#else
    //register remoteNotification types
    [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
     |UIRemoteNotificationTypeSound
     |UIRemoteNotificationTypeAlert];
#endif
    
    //for log
    [UMessage setLogEnabled:NO];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(checkFinished:)
                                                 name:UMFBCheckFinishedNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receiveNotification:)
                                                 name:nil
                                               object:nil];
}
- (void)receiveNotification:(id)receiveNotification {
    //    NSLog(@"receiveNotification = %@", receiveNotification);
}

- (void)checkFinished:(NSNotification *)notification {
    NSLog(@"class checkFinished = %@", notification);
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    //获取通话状态
//    CTCallCenter *callCenter = [[CTCallCenter alloc] init];
//    callCenter.callEventHandler=^(CTCall*call){
//
//        if (call.callState ==  CTCallStateIncoming){
//            
//            [self controllerd];
//            
//        }
//        
//
//    };
    
    [self setPush:launchOptions];
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
    
    
    _rarray =[[NSMutableArray alloc]init];
    _dataArray =[[NSMutableArray alloc]init];
    _imafg =[[UIImageView alloc]init];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(btckkopl:) name:@"textFieldgg" object:nil];
    
    NSUserDefaults* users =[NSUserDefaults standardUserDefaults];
    //[users removeObjectForKey:@"newusers1"];
    NSArray *array =[users objectForKey:@"newusers1"];
    NSLog(@"你好%@",array);
    
    //NSDictionary *dict =[array objectAtIndex:0];
    
    
    // NSLog(@"...%@",dict);
    //if([dict objectForKey:@"username"]==nil)
    if (!array)
        
        
    {
        JimViewController *userGuideViewController = [[JimViewController alloc] init];
        self.window.rootViewController = userGuideViewController;
    }else
    {
        splashScreen = [[UIImageView alloc] initWithFrame:self.window.bounds] ;
        if (DeviceHeight==480) {
            splashScreen.image = [UIImage imageNamed:@"shanping640.jpg"];
        }
        else
        {
            splashScreen.image = [UIImage imageNamed:@"shanping1136.jpg"];
        }
        
        [self.window addSubview:splashScreen];
        
        //        [UIView animateWithDuration:3.0 animations:^{
        ////            CATransform3D transform = CATransform3DMakeScale(1.0, 1.0, 1.0);
        ////            splashScreen.layer.transform = transform;
        //           // splashScreen.alpha = 1.0;
        //        } completion:^(BOOL finished) {
        //            [splashScreen removeFromSuperview];
        //            [self controllerd];
        //        }];
        //        [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(controllerd) userInfo:nil repeats:YES];
        [self performSelector:@selector(controllerd) withObject:nil afterDelay:3.0];
    }
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}
-(void)btckkopl:(NSNotification *)hgfd
{
    [self controllerd];
}
-(void)controllerd
{
    [splashScreen removeFromSuperview];
    CallViewController *call =[[CallViewController alloc]init];
    IponeViewController *ipone =[[IponeViewController alloc]init];
    MoneyViewController *money=[[MoneyViewController alloc]init];
    MeViewController *me =[[MeViewController alloc]init];
    UINavigationController *nvc2 =[[UINavigationController alloc]initWithRootViewController:ipone];
    UINavigationController *nvc3 =[[UINavigationController alloc]initWithRootViewController:money];
    UINavigationController *nvc4 =[[UINavigationController alloc]initWithRootViewController:me];
    NSMutableArray *array =[[NSMutableArray alloc]initWithObjects:call,nvc2,nvc3,nvc4, nil];
    _bar =[[UITabBarController alloc]init];
    _bar.viewControllers =[NSArray arrayWithArray:array];
    _bar.tabBar.hidden = YES;
    self.window.rootViewController =_bar;
    _mtb =[[MyTabBar alloc]init];
    //_mtb.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"tabbar.png"]];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(chajje:) name:@"hidendleTAb" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ch:) name:@"tex" object:nil];
    _mtb.frame =CGRectMake(0, DeviceHeight-49, DeviceWidth, 49);
    NSArray *buttonsImage = [[NSArray alloc] initWithObjects:
                             @"tab_0_nor.png",
                             @"tab_1_nor.png",
                             @"tab_2_nor.png",
                             @"tab_3_nor.png", nil];
    
    NSArray *buttonsSelectImage = [[NSArray alloc] initWithObjects:
                                   @"tab_0_pre.png",
                                   @"tab_1_pre.png",
                                   @"tab_2_pre.png",
                                   @"tab_3_pre.png",nil];
    NSArray *buttonsTitle =[[NSArray alloc]initWithObjects:@"",@"",@"",@"", nil];
    
    [_mtb createTabBarWithBackgroundImageName:@"tabbar.png" andButtonsImageName:buttonsImage andButtonsSelectImageName:buttonsSelectImage andButtonsTitle:buttonsTitle andSEL:@selector(btnClick:) andClass:self];
    [_bar.view addSubview:_mtb];
    //_tabView.view =_bar.view;
    UIView *view = [_mtb.subviews objectAtIndex:1];
    UIButton *btn = (UIButton *)[view.subviews objectAtIndex:0];
    btn.selected = YES;
}
-(void)ch:(NSNotification *)nte
{
    [_imafg removeFromSuperview];
    [_btn0 removeFromSuperview];
    [_btn1 removeFromSuperview];
    [_btn2 removeFromSuperview];
}
-(void)chajje:(NSNotification *)note
{
    _imafg.image=[UIImage imageNamed:@"tabbar.png"];
    _imafg.frame =CGRectMake(0, DeviceHeight-49, 320, 49);
    _imafg.userInteractionEnabled =YES;
    _btn1 =[UIButton buttonWithType:UIButtonTypeCustom];
    _btn1.frame =CGRectMake(100, 3, 120, 40);
    _btn1.layer.cornerRadius =10;
    [_btn1 addTarget:self action:@selector(btckko1) forControlEvents:UIControlEventTouchUpInside];
    [_btn1 setImage:[UIImage imageNamed:@"ic_end_call.png"] forState:UIControlStateNormal];
    [_imafg addSubview:_btn1];
    
    _btn0 =[UIButton buttonWithType:UIButtonTypeCustom];
    _btn0.frame =CGRectMake(0, 3, 100, 40);
    _btn0.layer.cornerRadius =10;
    [_btn0 addTarget:self action:@selector(btckko0) forControlEvents:UIControlEventTouchUpInside];
    [_btn0 setImage:[UIImage imageNamed:@"bohao.png"] forState:UIControlStateNormal];
    [_imafg addSubview:_btn0];
    
    _btn2 =[UIButton buttonWithType:UIButtonTypeCustom];
    _btn2.frame =CGRectMake(220, 3, 100, 40);
    _btn2.layer.cornerRadius =10;
    [_btn2 addTarget:self action:@selector(btckko2) forControlEvents:UIControlEventTouchUpInside];
    [_btn2 setImage:[UIImage imageNamed:@"lianxiren.png"] forState:UIControlStateNormal];
    [_imafg addSubview:_btn2];
    
    [self.window addSubview:_imafg];
    self.window.frame=CGRectMake(0, 0, DeviceWidth, DeviceHeight);
}
-(void)btckko2
{
    [_bar setSelectedIndex:1];
}
-(void)btckko0
{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"hid" object:_btn0];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"tex" object:_btn0];
    //
    //[_bar setSelectedIndex:0];
}
-(void)btckko1
{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"textFig" object:_btn1];
}
- (void)btnClick:(UIButton *)btn
{
    UIView *tabbarView = btn.superview.superview;
    for(UIView *view in tabbarView.subviews)
    {
        if(![view isKindOfClass:[UIImageView class]])
        {
            NSArray *subViews = view.subviews;
            UIButton *btn = (UIButton *)[subViews objectAtIndex:0];
            btn.selected = NO;
        }
    }
    btn.selected = !btn.selected;
    _bar.selectedIndex = btn.tag;
    if (btn.tag==0) {
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"hidden" object:btn];
        self.s=[[CallViewController alloc]init];
        self.s.txtNumber.text=nil;
    }
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"tex" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"hidendleTAb" object:nil];
}
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return UIInterfaceOrientationMaskPortrait;
}
- (BOOL)enableInputClicksWhenVisible
{
    return YES;
}
//禁止旋转屏幕
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{ return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(BOOL)shouldAutorotate
{
    return NO;
}
-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    
    
    NSLog(@"deviceToken:%@", token);
    [UMessage registerDeviceToken:deviceToken];
    NSLog(@"umeng message alias is: %@", [UMFeedback uuid]);
    [UMessage addAlias:[UMFeedback uuid] type:[UMFeedback messageType] response:^(id responseObject, NSError *error) {
        if (error != nil) {
            NSLog(@"11%@", error);
            NSLog(@"22%@", responseObject);
            NSLog(@"33%@", error.localizedDescription);
        }
    }];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    //[UMessage didReceiveRemoteNotification:userInfo];
    [UMFeedback didReceiveRemoteNotification:userInfo];
}


- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
